<template>
  <div class="flex justify-center index overauto"
       style="width: 100vw;height: 100vh;overflow-x: hidden;" v-if="props.isPlaceAnOrder">
    <div class="content">
      <div class="relative bg-[#F6F7FB]" style="background: linear-gradient(to bottom,#fff 2%,#f6f7fb 12%);">
        <div class="back-title" >
          <div class="relative back-box">
            <div class="absolute pt-[12PX] pl-[15PX] back-icon " @click="goBack">
              <el-icon><ArrowLeftBold size="16" /></el-icon>
            </div>
            <div class="back-title-text text-[16PX] text-center pt-[6PX]">
              {{getLanguage(props.product.language).view}}
            </div>
          </div>

        </div>


        <div class="px-[16PX]">
          <div class="px-[16PX] py-[14PX] bg-[#fff] details" style="border-radius: 0 0 12PX 12PX;">
            <div class="flex">
              <div class="imgbox">
                <img class="w-[108PX] h-[108PX] rounded-[12PX]" :src="product.cover" alt="" />
              </div>
              <div class="flex flex-col justify-between ml-[12PX] py-[5PX] info">
                <div class="text-[16PX] text-[#333] font-semibold tit">{{ product.title }}</div>
                <div class="price">
                  <div class="flex items-baseline ">
                    <div class="text-[14PX] text-[#FF0C06] mr-[2PX] font-semibold">{{areaInfo.currencySymbol}}</div>
                    <div class="text-[24PX] text-[#FF0C06] font-bold">{{ product.discountedPrice || product.originalPrice }}</div>
                  </div>
                  <div class="line-through text-[#999]" v-if="product.discountedPrice">{{areaInfo.currencySymbol}} {{ product.originalPrice }}</div>
                </div>
              </div>
            </div>



          <div class="px-[18px] mt-[15PX]" v-if="product.thaliFlag">
            <div> 型号：</div>
            <div class="mt-[15PX] flex flex-wrap">
              <div class="rounded-[8px] px-[10PX] py-[5PX] mr-[15PX] bg-[#FFF6F6] cursor-pointer"
                   v-for="(item,index) in product.thalis || []"
                   :key="index"
                   :class="`${ index == activeModel ? 'text-[#FF0C06] ' : 'text-[#333333]' }`"
                   :style="`border:solid 1px rgba(255,12,6,${ index == activeModel  ? 1 : 0 })`"
                    @click="selectSku(index)"
              >
                {{ item.nameForeign }}
              </div>
            </div>
          </div>
          <div class="mt-[15PX] px-[18px]"
               v-for="(item,index) in productInfo.newSpec[activeModel].productList || []"
               :key="index"

          >
            <div class="h-[36PX] flex items-center bg-[#F5F5F5] rounded-[8PX] pl-[10PX]" v-if="product.thaliFlag">
              第{{ index + 1 }}件 已选（<span class="text-[#FF0C06]">{{  item.sku.filter(item=>item.selected).length  }}</span>/{{  item.sku.length  }}）
            </div>
            <div class="bg-[#fff] detailPart" >
              <div class="">
                <div v-if="item.sku[0]?.nameForeign">
                  <div class="sku mt-[20PX]"
                      v-for="(item,index) in item.sku"
                      :key="index"
                  >
                    <div>{{ item.nameForeign }}</div>

                    <el-scrollbar>
                      <div class="list  flex flex-wrap mt-[15PX]" style="gap:8PX;">
                        <div
                          v-for="(it,idx) in item.list"
                          :key="idx"
                          @click="handleBtnClick({type:'sku',index,idx,item,it})"
                        >
                          <div
                            class="flex items-center px-[10PX] py-[2PX] rounded-[8PX] leading-[26PX] transition"
                            :class="`${idx+1 == item.selected ? 'bg-[#FFF8F6]' : 'bg-[#fff]' }`"
                            :style="`${idx+1 == item.selected ? 'border:1PX solid #FF3400' : 'border:1PX solid #E4E4E4'}`"
                          >
                            <div class="w-[26PX] h-[26PX] rounded-[3PX] imgbox" v-if="it.url">
                              <img class="object-contain w-auto h-full " :src="it.url" alt="" />
                            </div>
                            <div class=" text-[12PX] font-medium flex-center"
                                :class="[`${ idx+1 == item.selected ?  'text-[#FF3400]' : 'text-[#333]' }`,`${it.url?'ml-[10PX]':''}`]">
                              {{ it.nameForeign }}
                            </div>


                          </div>
                        </div>

                      </div>
                    </el-scrollbar>


                  </div>
                </div>
                <!-- 数量 -->
                <div class="sku mt-[20PX]" v-if="!product.thaliFlag">
                  <div>{{getLanguage(props.product.language).number}}</div>

                  <div class="mt-[15PX]">
                    <el-input-number :min="1" v-model="form.number" @change="handleAdd"/>
                  </div>
                </div>
              </div>


            </div>
          </div>
            <div class="mt-[20PX] px-[10PX] py-[7PX] bg-[#F9F9F9] text-[12PX] text-[#333] rounded-[6PX]" v-if="!product.thaliFlag && isAllPropertySelected().selectedItem[0]?.propertyValueForeign ">
              {{getLanguage(props.product.language).selected}}：{{  isAllPropertySelected().selectedItem[0]?.propertyValueForeign }} *{{form.number}}，{{getLanguage(props.product.language).totalPrice}}：{{ areaInfo.currencySymbol }}{{ computePrice.price }}
            </div>
          </div>

        </div>
        <div class="px-[16PX] mt-[14PX] block">
          <div class="px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]">
            <div class="text-[14PX] text-[#333] font-semibold">{{getLanguage(props.product.language).payMethod}}：</div>
            <div class="flex flex-wrap mt-[14PX]">
              <div class="py-[9PX] px-[20PX]  btnbox text-[#FF3400] activeBorder" >{{getLanguage(props.product.language).deliveryPay}}</div>
            </div>

          </div>
        </div>

        <div class="px-[16PX] mt-[14PX] block">
          <div class="px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]">
            <!-- 物流方式 -->
            <div class="text-[14PX] text-[#333] font-semibold">{{getLanguage(props.product.language).logisticsMethod}}：</div>
            <div class="flex flex-wrap mt-[14PX]" style="gap: 8PX;">
              <div v-for="(item,index) in logisticsList" :key="index" class="cursor-pointer"
                 @click="handleBtnClick({ type:'logistics',index })"
              >
                <div class="py-[9PX] px-[20PX]  commonBorder btnbox" :class=" index == form.activeLogistics ?'text-[#FF3400] activeBorder':'text-[#333] commonBorder'">{{ item.methodName }}</div>
              </div>

            </div>
            <!-- 配送说明 -->
            <div
              v-if="instruction.id"
              class="mt-[15PX] bg-[#FFF8EE] px-[20PX] py-[20PX] rounded-[8PX] text-[#8D5B0E] flex items-start"
              style="border: solid 1px rgba(141,91,14,0.2)">
              <div class="w-[15PX] h-[15PX] bg mr-[10PX]"
                  style="background-image: url(https://img.alicdn.com/imgextra/i2/801089336/O1CN01FXSiiT2IpwkHYqnkr_!!801089336.png);flex-shrink: 0;"></div>

              {{ instruction.stateInstructions }}

            </div>

            <div class="text-[14PX] text-[#333] mt-[20PX] font-semibold" v-if="!isNaN(computePrice.discountPrice) ">{{getLanguage(props.product.language).userInfo}}：</div>
            <div class="px-[18px] mt-[15PX]" v-if="!isNaN(computePrice.discountPrice) ">
              <div class="mt-[15px] templateForm">
                <el-form :model="form" :rules="rules" label-position="left" ref="formRef">

                  <el-row :gutter="24">
                    <el-col :xs="item.xs"
                            :xl="item.xl"
                            :lg="item.xl"
                            v-for="(item,index) in inputConfig"
                            :key="index"

                    >

                      <el-form-item :prop="item.code"
                                    v-if="(((item.directly && logisticsList[form.activeLogistics]?.directlyStatus == 0) || !item.directly) ? true : false ) && item.show"
                                    :label="item.name"
                      >

                        <el-input v-model="form[item.code]"
                                  :placeholder="item.name"
                                  :min="0"
                                  v-if="!item.type || item.type == 'text'"
                                  :disabled="(item.code == 'detailAddress' ? (logisticsList[form.activeLogistics]?.directlyStatus == 0 ? true  :false)  : false) "
                        />
                        <el-select v-model="form[item.code]"
                                  :placeholder="item.name"
                                  v-if="item.type == 'select'"
                                  @change="onChange(item.code)"
                        >

                          <el-option v-for="(it,idx) in item.list" :key="idx" :value="it[item.value]"
                                    :label="it[item.label]"/>

                        </el-select>

                        <el-input
                          :placeholder="item.name" v-model="form[item.code]"
                          v-if="item.type == 'textarea'"
                          type="textarea"
                          :rows="5"
                          resize="none"
                        />

                      </el-form-item>
                    </el-col>
                  </el-row>

                </el-form>
              </div>


            </div>


          </div>
        </div>
        <div class="px-[16PX] mt-[14PX] pb-[65PX] block" >
          <div class="px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]"  v-if="!isNaN(computePrice.discountPrice) ">
            <div class="flex items-center justify-between">
              <div class="text-[14PX] label">{{getLanguage(props.product.language).orderInfo}}：{{  }} {{   }}</div>
              <div class="flex items-center val">
                <div class="text-[12PX]  text-[#fff] px-[7PX] py-[4PX] rounded-[13PX] mr-[10PX] yhbtn" v-if="product.discountedPrice" style="background:  linear-gradient( 270deg, #FF3400 0%, #FD4442 100%);">{{getLanguage(props.product.language).havedCoupon}}</div>
                <div class="flex items-baseline">
                  <span class="text-[14PX]  text-[#FF0C06] mr-[4PX]">{{getLanguage(props.product.language).total}}</span>
                  <div class="text-[20PX] text-[#FF0C06] font-bold">{{ areaInfo.currencySymbol }}{{ computePrice.discountPrice }}</div>
                </div>
              </div>
            </div>
            <div class="flex justify-between mt-[10PX]  items-center">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).productNameTag}}<span class="text-[#C7C7C7] text-[12PX]">({{getLanguage(props.product.language).total}}{{form.number}}{{getLanguage(props.product.language).numberUnit}})</span>
              </div>
              <div class="flex items-center val">
                <div class="flex text-[14PX] text-[#333] items-baseline">
                  {{getLanguage(props.product.language).originPrice}} {{ areaInfo.currencySymbol }} {{ computePrice.price }}
                </div>
              </div>
            </div>
            <!-- 手续费 -->
            <div class="flex justify-between mt-[10PX]  items-center" v-if="product.commission">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).commission}}
              </div>
              <div class="flex items-center val">
                <div class="flex text-[14PX] text-[#333] items-baseline">
                 {{ areaInfo.currencySymbol }} {{  product.commission || 0 }}
                </div>
              </div>
            </div>
             <!-- 運费 ---修改 -->
             <!-- <div class="flex justify-between mt-[10PX]  items-center" v-if="!isRemote">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).shippingFee}}
              </div>
              <div class="flex items-center val">
                <div class="flex text-[14PX] text-[#333] items-baseline">
                 {{ areaInfo.currencySymbol }} {{  product.thaliFlag? product.thalis[activeModel].shippingFee  : product.shippingFee || 0 }}
                </div>
              </div>
            </div> -->
            <!-- 偏遠地區郵费 -->
            <div class="flex justify-between mt-[10PX]  items-center" v-if="product.shippingFee">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).shippingFee}}
              </div>
              <div class="flex items-center val">
                <div class="flex text-[14PX] text-[#333] items-baseline">
                 {{ areaInfo.currencySymbol }} {{ computePrice.shippingFee || 0 }}
                </div>
              </div>
            </div>
            <!-- 优惠 -->
            <div class="flex justify-between mt-[10PX]  items-center" v-if="product.discountedPrice">
              <div class="text-[14PX] label">
                {{getLanguage(props.product.language).discount}}
              </div>
              <div class="flex items-center val"  @click="handleArrow">
                <div class="flex text-[14PX] text-[#333] mr-[4PX] items-baseline">
                  <!-- -{{ areaInfo.currencySymbol }} {{ computePrice.originalPrice - computePrice.discountPrice || product.originalPrice - computePrice.discountPrice }} -->
                  -{{ areaInfo.currencySymbol }}{{ isPickup? computePrice.lessPrice + product.couponAmount :computePrice.lessPrice}}
                </div>

                <el-icon v-if="showCoupon"><ArrowDown size="16"  /></el-icon>
                <el-icon  v-else  ><ArrowUp size="16"  /></el-icon>
              </div>
            </div>
            <div class="mt-[6PX]" v-if="showCoupon">
              <div class="rounded-[12PX] px-[16PX] py-[6PX] bg-[#FAFAFA]">
                <div class="flex justify-between py-[4PX] items">
                  <div class="label">{{getLanguage(props.product.language).promotion}}</div>
                  <div class="text-[#FF3400] val">
                    -{{ areaInfo.currencySymbol }}{{ computePrice.lessPrice }}
                  </div>
                </div>
                <div class="flex justify-between py-[4PX] items" v-if="isPickup">
                  <div class="label"> {{  getLanguage(props.product.language).coupon}}</div>
                  <div class="val" :class="product.couponAmount?'text-[#FF3400]':'text-[#333]'">

                    {{ product.couponAmount?`-${areaInfo.currencySymbol} ${product.couponAmount}`:  getLanguage(props.product.language).disable }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="mt-[6PX] px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]"  v-if="policyList && policyList.length>0">
            <div class=" mt-[30PX] pb-[30PX]">
            <el-collapse v-model="activeNames"
                        v-if="policyList && policyList.length>0">
              <el-collapse-item :title="item.title" :name="item.id" v-for="(item,index) in policyList.filter(policy=>policy.type==4)"
                                :key="index">
                <div v-html="item.detail"></div>
              </el-collapse-item>

            </el-collapse>
            </div>
          </div>

        </div>
       
        <div class="fixed left-[50%] translate-x-[-50%] bottom-0  z-10  w-[100%] max-w-[640PX]  h-[40PX] flex-center bg-[#FF0C06] text-[#FFF]"
             @click="handleBtnClick({type:'submit'})"
             v-if="!isNaN(computePrice.discountPrice)"
             >
             {{getLanguage(props.product.language).submit}}

        </div>
        <div class="fixed left-[50%] translate-x-[-50%] bottom-0  z-10  w-[100%] max-w-[640PX]  h-[40PX] flex-center bg-[#ccc] text-[#FFF]"
            v-else
             >
             {{getLanguage(props.product.language).undisabled}}

        </div>

      </div>
    </div>
  </div>


</template>
<script lang="ts" setup>
import { FormInstance } from 'element-plus'
import {useMessage} from "@/hooks/web/useMessage";
import { ArrowLeftBold } from '@element-plus/icons-vue'
import { ArrowDown } from '@element-plus/icons-vue'
import { ArrowUp } from '@element-plus/icons-vue'
import { getLanguage } from "@/utils/langue";
import {deepCopy} from "@/utils";

const message = useMessage();
const props = defineProps({
  isPlaceAnOrder: {
    type: Boolean,
    default: false
  },
  product: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  areaInfo: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  skuInfo: {
    type: Array,
    required: false,
    default: () => []
  },
  hasProvince:{
    type: Boolean,
    default:true,
  },
  //原商品列表sku
  originalSku: {
    type: Array,
    required: false,
    default: () => []
  },
  provinceList: {
    type: Array,
    required: false,
    default: () => []
  },
  logisticsList: {
    type: Array,
    required: false,
    default: () => []
  },
  storeList: {
    type: Array,
    required: false,
    default: () => []
  },
  globalConfig:{
    type: Object,
    required: false,
    default: () => {}
  },
  isPickup:{
    type: Boolean,
    default: false
  },
  remoteList:{
    //偏远地区列表
    type: Array,
    default: () => []
  },
  policyList: {
    type: Array,
    required: false,
    default: () => []
  },
  instruction: {
    type: Object,
    required: false,
    default: () => {}
  },

});


const productInfo = ref({})

const formRef = ref<FormInstance>()

const isRemote = ref(false)

const emit = defineEmits(['confirm', 'execute','update:isPlaceAnOrder']);
const isShow = ref(false)

const showCoupon = ref(false)

const activeNames = ref([''])

const config = ref([
  {
    name: "免运费",
  },
  {
    name: "货到付款",
  },
  {
    name: "15天鉴赏期",
  },
  {
    name: "正品保证",
  }
])


const skuList = ref([])

const activeModel = ref(0);


const initConfig = [
  {
    name: getLanguage(props.product.language).name,
    code: "customerName",
    xs: 24,
    xl: 24,
    required: true,
    show:true,
  },
  {
    name: getLanguage(props.product.language).phone,
    code: "customerPhone",
    xs: 24,
    xl: 24,
    required: true,
    show:true,
  },
  {
    name: getLanguage(props.product.language).area,
    code: "areaName",
    type: "select",
    label: "name",
    value: "value",
    xs: 24,
    xl: 8,
    required: true,
    show:true,
    list:[
      {
        name: props.product.areaName,
        value: props.product.areaName
      }
    ]
  },
  {
    name: getLanguage(props.product.language).areaName,
    code: "cityName",
    type: "select",
    label: "name",
    value: "name",
    xs: 24,
    xl: 8,
    required: true,
    show:props.hasProvince,
  },
  {
    name: getLanguage(props.product.language).cityName,
    code: "regionName",
    type: "select",
    label: "name",
    value: "name",
    xs: 24,
    xl: 8,
    required: true,
    show:props.hasProvince,
  },
  // {
  //   name: "选择地区",
  //   code: "regionName",
  //   type: "select",
  //   label: "name",
  //   value: "id",
  //   xs: 24,
  //   xl: 8,
  //   required: true,
  //   show:true,
  // },
  {
    name: getLanguage(props.product.language).selectStore,
    code: "addressId",
    type: "select",
    label: "name",
    value: "id",
    xs: 24,
    xl: 24,
    required: false,
    directly: true,
    show:true,
  },
  {
    name:  getLanguage(props.product.language).address,
    code: "detailAddress",
    xs: 24,
    xl: 24,
    required: true,
    show:true,
  },
  {
    name: getLanguage(props.product.language).message,
    code: "message",
    type: "textarea",
    xs: 24,
    xl: 24,
    required: false,
    show:true,
  }
]

const inputConfig = ref([...initConfig]);

/**
 * 优惠信息展开/收起
*/
const handleArrow = ()=>{
  showCoupon.value = !showCoupon.value
}


const computePrice = computed(() => {
  //获取sku列表
  //查看是否全部选中
  let isAllSelected = isAllPropertySelected().isAllSelected
  const shippingFeeValue = Number(
    isRemote.value? props.product.remotePostage:
    props.product.thaliFlag
      ? props.product.thalis[activeModel.value]?.shippingFee || 0
      : props.product.shippingFee || 0
  );
  if (isAllSelected) {

    let selectArr =  isAllPropertySelected().selectedItem;
    let totalOriginalPrice = 0;
    let totalDiscountPrice = 0;

    if(props.product.thaliFlag != 1){
      selectArr.forEach(item=>{
        totalOriginalPrice+= item?.price * parseInt(form.value.number);
        totalDiscountPrice+= item?.discountedPrice * parseInt(form.value.number);
      })
      console.log(totalDiscountPrice,selectArr,'=====================>1')
    }else{
      totalOriginalPrice=Number( props.product.thalis[activeModel.value].originalPrice);
      totalDiscountPrice = Number(props.product.thalis[activeModel.value].discountedPrice);
      console.log(totalDiscountPrice,'=====================>2')
    }
    
    if(!totalDiscountPrice) totalDiscountPrice = totalOriginalPrice
   
    if (props.product.couponAmount && props.isPickup) {
      totalDiscountPrice -= (props.product.couponAmount || 0)
    }

    return {
      price:totalOriginalPrice.toFixed(2),//原价
      discountPrice:
        (totalDiscountPrice +   (shippingFeeValue || 0) +(props.product.commission || 0)).toFixed(2),//折扣价
      remotePostage:(isRemote.value? (props.product.remotePostage||0) : 0).toFixed(2),//远程费
      // shippingFee: (props.product.thaliFlag?props.product.thalis[activeModel.value].shippingFee  : props.product.shippingFee || 0).toFixed(2),//运费
      shippingFee: shippingFeeValue.toFixed(2),
      commission:(props.product.commission||0).toFixed(2),//佣金
      lessPrice: (totalOriginalPrice - totalDiscountPrice).toFixed(2),//优惠价格
    }




  } else {

    if(props.product.thaliFlag){
      //如果是套餐需要根据选中的套餐价格变化
      const price = props.product.thalis[activeModel.value].discountedPrice ? props.product.thalis[activeModel.value].discountedPrice : Number(props.product.combo[activeModel.value].originalPrice).toFixed(2)//原价
      return {
        price:Number(props.product.thalis[activeModel.value].originalPrice).toFixed(2),//原价
        // discountPrice:(Number( props.product.thalis[activeModel.value].discountedPrice) - (props.isPickup ? (props.product.couponAmount || 0) : 0) ).toFixed(2),//折扣价
        discountedPrice: Number(price +   (shippingFeeValue || 0) +(props.product.commission || 0)).toFixed(2),
        remotePostage: Number(isRemote.value? (props.product.remotePostage||0) : 0).toFixed(2),//远程费
        shippingFee: shippingFeeValue.toFixed(2),
        commission:Number(props.product.commission||0).toFixed(2),//佣金
        lessPrice: Number(props.product.originalPrice - (props.product.discountedPrice || 0)).toFixed(2),//优惠价格
      }
    }else{
      const price = props.product.discountedPrice ? props.product.discountedPrice : Number(props.product.originalPrice).toFixed(2)//原价
      return {
        price:price,//原价
        discountedPrice: Number(price +  (shippingFeeValue || 0) +(props.product.commission || 0)).toFixed(2),
        remotePostage:Number(isRemote.value? (props.product.remotePostage||0) : 0).toFixed(2),//远程费
        shippingFee: shippingFeeValue.toFixed(2),//运费
        commission:Number(props.product.commission||0).toFixed(2),//佣金
        lessPrice: Number(props.product.originalPrice - (props.product.discountedPrice || 0)).toFixed(2),//优惠价格
      }
    }


  }
})


const show = () => {
  isShow.value = true
}
const goBack = () => {
  emit('update:isPlaceAnOrder', false)
}
/**
 * 计算rules
 * */
const rules = computed(() => {

  let obj = {}
  inputConfig.value.forEach(item => {
    if (item.required) {
      obj[item.code] = [{
        required: true,
        message: `${item.type == 'select' ?  getLanguage(props.product.language).selectTips : getLanguage(props.product.language).inputTips}${item.name}`,
        trigger: `${item.type == 'select' ? 'change' : 'blur'}`
      }]
    }

  })

  console.log(obj, "===")
  return obj
})

let initForm = {
  number: 1,
  activeLogistics: 0,
  areaName:props.product.areaName,
}

const form = ref({
  ...initForm
})

/**
 * 数量增加按钮
*/
const handleAdd = ()=>{
  if(!isAllPropertySelected().selectedItem[0]?.propertyValueForeign){
    form.value.number = 1
    message.error('请选择规格')
    return;
  }
}

const handleBtnClick = (e) => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }
}

const isAllPropertySelected = () => {
  let selectedItem =  []
  let isAllSelected= true;

  let productList = deepCopy( productInfo.value.newSpec[activeModel.value].productList || []);

  productList.forEach((item) => {
    let skuList = item.sku || [];
    for(let i=0;i<skuList.length;i++){
      if(!skuList[i].selected){
        isAllSelected=false;
        break;
      }
    }
  })

  if(isAllSelected){
    productList.forEach((item,index) => {
      let skuList = item.sku || [];

      //拿到原来的规格
      let oldSpes = productInfo.value.thalis[activeModel.value].thaliDetailList[index].specs || [];

      let selectedArr = [];

      if(oldSpes.length == 1){
        selectedItem = deepCopy(oldSpes);
      }else{
        skuList.forEach(it => {
          selectedArr.push(it.list[it.selected-1])
        })

        let name = selectedArr.map(item=>item.name).join('§');

        let  selectedObj = oldSpes.find(at=>{
          return at.propertyValue == name
        })
        selectedItem.push(selectedObj);

      }


    })
  }

  return {
    selectedItem,
    isAllSelected
  }
}

const selectSku = (index:number)=>{
  console.log(index,"index")
  activeModel.value = index;
}

const fn = {
  // pickupCoupon() {
  //   if (!isPickup.value) {
  //     isPickup.value = true;
  //     message.success("领取成功")
  //   }
  // },
  async submit() {
    try {
      let res = await formRef.value.validate();

      let item = inputConfig.value.find(item => {
        return item.code == 'cityName'
      })
      //查看有没有v选择sku
      if (isAllPropertySelected().isAllSelected) {

        let addressItem = inputConfig.value.find(at=>{
          return at.code == "addressId"
        })
        let address = null;
        if(addressItem){
          let lis = addressItem.list;

          if(form.value.addressId){
            address = lis.find(at=>{
              return at.id == form.value.addressId
            })?.name
          }
        }
        console.log('isRemoteisRemote',isRemote.value)
        emit('execute', {
          type: 'confirm',
          form: form.value,
          address:address,
          skuList: skuList.value,
          priceInfo: computePrice.value,
          isPickup: props.isPickup,
          regionList: item.list,
          regionName: item.list.find(at => at.id == form.value.regionName)?.name,
          selectedProperty: isAllPropertySelected().selectedItem,
          thaliId: productInfo.value.thaliFlag == 1 ?   productInfo.value.thalis[activeModel.value]?.id : '',
          thaliName: productInfo.value.thaliFlag == 1 ?   productInfo.value.thalis[activeModel.value]?.nameForeign : '',
          thaliPrice: productInfo.value.thaliFlag == 1 &&   productInfo.value.thalis[activeModel.value]?.discountedPrice ?  productInfo.value.thalis[activeModel.value]?.discountedPrice : productInfo.value.thalis[activeModel.value]?.originalPrice,
          isRemote: isRemote.value,
          success() {
            if(props.globalConfig.orderDelectSteat == 1){
              form.value = {
                ...initForm
              }
            }

          }
          //其他 sku等信息
        })
      } else {
        message.error("请选择sku");
      }


    } catch (e) {
      console.log(e)
      for (let i in e) {
        message.error(e[i][0].message);
        return
      }
    }
  },
  logistics({index}) {
    form.value.areaName = ''
    form.value.cityName = ''
    form.value.activeLogistics = index;
    formRef.value?.resetFields();

  },
  sku({item, it, index, idx}) {
    item.selected = idx + 1;
  }
}

const onChange = code => {
  if (code == 'areaName') {
    // form.value.cityName = ''
    // form.value.regionName = ''
    // //生成
    // let item = inputConfig.value.find(at => {
    //   return at.code == 'cityName'
    // })
    // //获取市
    // let it = props.provinceList.find(at => {
    //   return at.name == form.value[code];
    // })
    // if(item){
    //   item.list = it.list || [];
    // }

    // item = inputConfig.value.find(at => {
    //   return at.code == 'regionName'
    // })
    // if(item){
    //   item.list = []
    // }
    // item = inputConfig.value.find(at => {
    //   return at.code == 'addressId'
    // })
    // if(item){
    //   item.list = [];
    // }

  } else if (code == 'cityName') {
    form.value.regionName = ''

    let item = inputConfig.value.find(at => {
      return at.code == 'regionName'
    })

    let item1 = inputConfig.value.find(at => {
      return at.code == 'cityName'
    })

    console.log('cityName',form.value.cityName)

    let it = item1.list.find(at => {
      return at.name == form.value.cityName
    })
    if(item){
      item.list = it.list
    }


    item = inputConfig.value.find(at => {
      return at.code == 'addressId'
    })
    if(item){
      item.list = [];
    }

  } else if (code == 'regionName') {


  } else if (code == 'addressId') {
    let it = props.storeList.find(at => {
      return at.id == form.value[code]
    })

    form.value.detailAddress = it.detailedAddress
  }
}


const computeSku = (pindex,index) => {
  try {
    let skuInfo = props.product.thalis[pindex].thaliDetailList[index].specs || [];

    let list = deepCopy(skuInfo)
    if (list.length > 0) {
      let arr = []

      let sizeArr = (list[0].name||'').split(/§/gi)

      let sizeFoeignArr = (list[0].nameForeign ||'').split(/§/gi)
      sizeArr.forEach((item, index) => {
        //找到 不重复的 属性
        let obj = {
          name: item,
          nameForeign: sizeFoeignArr[index],
          list: []
        }
        list.forEach((it) => {
          let propertyArr = (it?.propertyValue||'').split(/§/gi)
          let propertyValueForeignArr = (it?.propertyValueForeign||'').split(/§/gi)
          let imgArr = (it?.picture ||'').split(/,/gi)
          let isIn = obj.list.find((at) => {
            return at.nameForeign == propertyValueForeignArr[index]
          })
          if (!isIn) {
            obj.list.push({
              name: propertyArr[index],
              nameForeign: propertyValueForeignArr[index],
              url: (imgArr && imgArr.length > 0 && imgArr[index]) || ''
            })
          }
        })

        arr.push(obj)
      })
      if (arr.length == 1) {
        arr[0].selected = 1
      }
      return arr
    } else {
      return []
    }
  } catch (e) {
    console.log(e)
  }
}

watch(() => props.provinceList, () => {
  let item = inputConfig.value.find(at => {
    return at.code == 'cityName'
  })
  item.list = props.provinceList
}, {
  deep: true,
  immediate: true
})

watch(() => [form.value.activeLogistics, form.value.regionName], () => {
  console.log('watch',form.value.regionName)
  if (form.value.regionName) {
    isRemote.value = props.remoteList.find(at => {
      return at.city == form.value.regionName
    })? true : false
    if (props.logisticsList[form.value.activeLogistics]?.directlyStatus == 0) {
      //获取store
      emit('execute', {
        type: 'store',
        data: form.value,
        callback(storeList) {
          let item = inputConfig.value.find(at => {
            return at.code == 'addressId'
          })
          item.list = storeList.map(item => {
            return {
              id:item.id,
              name: item.storeName,
              address: item.detailedAddress
            }
          })
        }
      })
    }

  }
}, {
  deep: true,
  immediate: true
})


watch(() => props.skuInfo, () => {
  if(props.skuInfo.length===0){
    skuList.value = props.originalSku
  }else{
    skuList.value = props.skuInfo;
  }

}, {
  deep: true,
  immediate: true
})

const initProductInfo = () => {
  let product = deepCopy(props.product);
  product.newSpec = [];
  product.thalis.forEach((item,pindex) => {
    let obj = {
      ...item,
      productList: []
    }
    //循环商品
    item.thaliDetailList.forEach((it, idx) => {
      obj.productList.push({
        sku: computeSku(pindex, idx)
      })
    })
    product.newSpec.push(obj)
  })

  console.log(product,"ppppppppppppppp")
  productInfo.value = product
}


watch(() => props.product, () => {
  initProductInfo();
}, {
  deep: true,
  immediate: true
})
//抛出show
defineExpose({
  show
})
</script>
<style>
</style>
<style scoped lang="less">
.commonBorder{
  border: 1PX solid #dedede;
  border-radius: 12PX;
}
.activeBorder{
  border: 1PX solid #FF3400;
  border-radius: 12PX;
}
.back-title{
  width: 100%;
  height: 42PX;
  background-color: #fff;
}
.back-title-text{
  img{
    width: 7PX;
    height: 7PX;
  }
  span,p{
    color: #073064;
    font-size: 7PX;
  }
}


:deep(.el-form-item__label){
  font-size: 14PX;
  height: 30PX;
}









@import "@/common";

.index {
  .content {
    width: 640PX;
    height: 100%;

    .top-title {
      font-size: 14PX !important;
      .btn-promotion{
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 6PX;
        width: 40PX;
        line-height: 40PX;
        height: 18PX;
        background: #FFF5F5;
        border-radius: 3PX;
        border: 1px solid #FF0C06;
        color: #FF0C06;
        font-size: 12PX;
      }

      .bar {
        width: 4PX;
      }
    }

    .subTitle {
      font-size: 10PX !important;
    }

    .swiper {
      width: 100%;
      height: 640PX;

      .swiper-item {
        width: 100%;
        height: 640PX;
      }

      .benefit {
        width: 100%;
        height: 64PX;

        .qianggou-num {
          padding: 5PX 12PX;
        }
      }

      .cycle {
        width: 27PX;
        height: 27PX;
        border-radius: 5PX;
        background: #FD4442;
      }
    }


    .price {
      font-size: 28PX;
      margin-bottom: -5PX;
    }

    // .coupon {
    //   width: 100%;
    //   height: 45PX;
    //   padding-left: 60PX;
    // }


    .icons {
      width: 14PX;
      height: 14PX;
    }
  }

  .ft12 {
    font-size: 12PX !important;
  }

}

@media screen and (max-width: 640PX) {
  .index {
    .content {
      width: 100%;

      .swiper {
        width: 100vw;
        height: 100vw;

        .swiper-item {
          width: 100vw;
          height: 100vw;
        }
      }
    }

    .ft12 {
      .font(18);
    }

  }
  :deep(.el-form-item__label){
    font-size: 14PX;
    height: 20PX;
  }
}

:deep(.el-carousel) {
  width: 100%;
  height: 100%;

  .el-carousel__container {
    width: 100%;
    height: 100%;
  }
}

:deep(.el-input-number) {
  width: 135PX;
  height: 30PX;

  .el-input-number__decrease, .el-input-number__increase {
    width: 28PX;
    height: 28PX;
    border-radius: 0PX;
  }

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
  }

  .el-icon {
    font-size: 14PX;
  }

}

:deep(.el-input) {
  height: 30PX;

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
    border-radius: 12PX;
    box-shadow: none;
  }


}

:deep(.el-textarea ) {
  height: 60PX !important;

  .el-textarea__inner {
    height: 60PX !important;
    font-size: 12PX;
    box-shadow: none;
    border:1PX solid #e5e5e5;
    border-radius: 12PX !important;
    padding: 4PX 10PX;
  }

}


:deep(.el-select) {
  height: 30PX !important;
  .el-select__wrapper{
    box-shadow: none;
    border:1PX solid #e5e5e5;
    border-radius: 12PX !important;
  }
  .el-select__selected-item, .el-input__inner, .el-select__wrapper {
    height: 30PX !important;


  }

  .el-select__placeholder {
    display: flex !important;
    align-content: center;
    align-items: center;
  }

}

:deep(.el-form-item) {
  margin-bottom: 0PX;
  margin-top: 15PX;
  flex-direction: column;
}

:deep(.el-input__wrapper){
  padding: 0PX 10PX;
  box-shadow: none;
  border:1PX solid #e5e5e5;
  border-radius: 12PX !important;
  outline: unset;
}
:deep(.el-select__wrapper){
  padding: 0 10PX;
}

</style>
